<script setup>
import Editor from '@tinymce/tinymce-vue'

const props = defineProps({
  value: String,
  height: {
    type: String,
    default: 'var(--main-body-box-height)',
  }
})

const content = ref(props.value)

const emit = defineEmits(['update:value'])

watch(content, (newValue) => {
  emit('update:value', newValue)
})

const tinymceEditor = ref(null)

const editInit = reactive({
  language: 'zh-CN',
  plugins: [
    'lists', 'link', 'image', 'table', 'code', 'wordcount', 'preview',
    'searchreplace', 'fullscreen', 'visualblocks',
    'visualchars', 'insertdatetime', 'anchor', 'nonbreaking', 'pagebreak',
    'emoticons', 'charmap', 'codesample', 'media', 'quickbars', 'autolink',
  ],
  menu: {
    file: {title: 'File', items: 'export print'},
    edit: {title: 'Edit', items: 'undo redo | cut copy paste pastetext | selectall | searchreplace'},
    view: {title: 'View', items: 'code | visualaid visualchars visualblocks | preview fullscreen'},
    insert: {
      title: 'Insert',
      items: 'image link media codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor | insertdatetime'
    },
    format: {
      title: 'Format',
      items: 'bold italic underline strikethrough superscript subscript codeformat | styles blocks fontfamily fontsize align lineheight | forecolor backcolor | removeformat'
    },
    tools: {title: 'Tools', items: 'code wordcount'},
    table: {title: 'Table', items: 'inserttable | cell row column | tableprops deletetable'},
  },
  toolbar: [
    'removeformat selectall | aligncenter alignleft alignright alignjustify | bold italic underline strikethrough blockquote |blocks | fontfamily fontsize | forecolor backcolor | table | code preview fullscreen'
  ],
  tinycomments_mode: 'embedded',
  branding: false,
  statusbar: true,
  promotion: false,
  onboarding: false,
  quickbars_insert_toolbar: false,
  quickbars_selection_toolbar: 'bold italic | blocks | quicklink blockquote | alignright',
  init_instance_callback: (editor) => {
    tinymceEditor.value = editor
  }
})

const insertContent = (content) => {
  return tinymceEditor.value.insertContent(content)
}

const focus = () => {
  tinymceEditor.value.focus()
}

defineExpose({insertContent, focus})

</script>

<template>
  <Editor
      api-key="xvm9rbjpj2r2mz1cl4e4z1o57l5cb7m48jt3uu6pty0jfdll"
      :id="tinymceId"
      v-model="content"
      :init="editInit"
      style="width: 100%;"
      :style="{height}"/>
</template>

<style lang="scss">
.tox {
  z-index: 50000 !important;
}

p {
  margin: 0 auto !important;
}
</style>